// 购物车模块
import axios from 'axios';
const cartModule = {
    // 开启子模块的命名空间————防止命名冲突 state mutations actions getters modules
    namespaced: true,
    state() {
        return {
            goodsList: []
        }
    },
    mutations: {
        setGoodsList(state, newList) {
            state.goodsList = newList
        },
        // mutations  只能接受两个参数，由于这里需要多个参数，所以第二个参数是一个对象
        // 对象中 可包含多个属性
        ck(state, obj) {
            state.goodsList[obj.index].goods_state = obj.checked
        },
        sel(state, bool) {
            state.goodsList.forEach(item => item.goods_state = bool)
        },
        addGoodsItem(state, index) {
            state.goodsList[index].goods_count++
        },
        subGoodsItem(state, index) {
            state.goodsList[index].goods_count--
        }
    },
    actions: {
        async asyncsetGoodsList(store) {
            const res = await axios({
                url: 'https://www.escook.cn/api/cart'
            })
            store.commit('setGoodsList', res.data.list)
        }
    },
    getters: {
        totalCount(state) {
            return state.goodsList.reduce((sum, obj) => {
                if (obj.goods_state) {
                    sum += obj.goods_count
                }
                return sum
            }, 0)
        },
        totalPrice(state) {
            return state.goodsList.reduce((sum, obj) => {
                if (obj.goods_state) {
                    sum += obj.goods_count * obj.goods_price
                }
                return sum
            }, 0)
        },
        ckall(state) {
            //    小选决定大选
            return state.goodsList.every(item => item.goods_state)
        }
    },
}

export default cartModule